#----------------------------------
# Step1: Get INFO
#----------------------------------
import urllib2
import os

baseurl = 'https://svn.sinaapp.com/tgsmpss/1'
user    = 'tiangao1102@163.com'
passwd  = 'stg@919'
tfile    = 'README.txt'

realm = "Subversion Repositories"
auth = urllib2.HTTPBasicAuthHandler()
auth.add_password(realm, baseurl, user, passwd)
opener = urllib2.build_opener(auth, urllib2.CacheFTPHandler)
urllib2.install_opener(opener)
 
 
#----------------------------------
# Step3: Create Folder
#----------------------------------
folderName = "svnFile"
if not os.path.exists(folderName):
    os.mkdir(folderName)

 
#----------------------------------
# Step4: Get File
#----------------------------------
def getFile(tfile):
    # ignore the blank line
    if tfile != "":
        url = "%s/%s"%(baseurl,tfile)
        print url
        try:
            data = urllib2.urlopen(url)
 
            fw = open("%s/%s"%(folderName,tfile),'w')
            fw.write(data.read())
            fw.close()
 
            print "Download: %s."%tfile
 
        except urllib2.HTTPError, e:
            # HTTPError is a subclass of URLError
            # need to catch this exception first
            mesg = str(e).split(" ")
            errCode = mesg[2].rstrip(":")
             
            if errCode == "401":
                # HTTP Error 401: basic auth failed
                print "Can not login in, please check the user and passwd"
            elif errCode == "404":
                # HTTP Error 404: Not Found
                print "Not Found: %s"%tfile
            else:
                print e
                print "Failed to download %s"%tfile
 
        except urllib2.URLError, e:
            # 1.SVN server is down 
            # 2.URL is not correct
            print e
            print "Please check SVN Server status and baseurl"

getFile(tfile)

raw_input("")